<?php
require_once('../includes/init.php');

if($_GET['act']=='logout')
{
	unset($_SESSION[SESSION_PREFIX]);
	unset($_COOKIE['YJT_ID']);

	header("Location: /new/index.php");
}

if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['act'] == 'post')
{
	$username = trim($_POST['username']);
	$password = $_POST['pwd'];
	$captcha  = $_POST['imgcode'];
	
	$res_arr = array(
		'code' => 200,
		'msg'  => '',
	);
	
	if($username=='')
	{
		$res_arr = array(
			'code' => 0,
			'msg' => '用户名不能为空'
		);
		die(json_encode($res_arr));
	}
	if($password=='' || strlen($password)<6 || strlen($password)>20)
	{
		$res_arr = array(
			'code' => 0,
			'msg' => '密码必须是6到20个字符或数字'
		);
		die(json_encode($res_arr));
	}
	
	//验证码
	require(ROOT_PATH . '/includes/securimage/securimage.php');
    $securimage = new Securimage();
    if ($securimage->check($captcha) == false) {
    	$res_arr = array(
			'code' => 0,
			'msg' => '验证码错误'
		);
		die(json_encode($res_arr));
    }
	
	$sql = "SELECT `user_id`,`username`,`email`,`password`,`is_admin` FROM `user` WHERE `username`='".$username."' OR `email`='".$username."';";
	$user = $db->getRow($sql);
	if(!empty($user))
	{
		if(md5($password)<>$user['password'])
		{
			$res_arr = array(
				'code' => 0,
				'msg' => '密码错误'
			);
			die(json_encode($res_arr));
		}
		else
		{
			$_SESSION[SESSION_PREFIX]['user_id'] 	= $user['user_id'];
			$_SESSION[SESSION_PREFIX]['username'] 	= $user['username'];
			$_SESSION[SESSION_PREFIX]['email']      = $user['email'];
			$_SESSION[SESSION_PREFIX]['is_admin']      = $user['is_admin'];
			
			$sql = "UPDATE `cart` SET `user_id`='".$user['user_id']."' WHERE `session_id`='".$_SESSION[SESSION_PREFIX]['session_id']."';";
			$db->query($sql);
			
			$sql = "INSERT INTO `user_log` (`id`, `user_id`, `tm`, `fromip`, `urlname`, `agent`) VALUES (NULL, '".$user['user_id']."', NOW(), '".$_SERVER['REMOTE_ADDR']."', '', '".$_SERVER['HTTP_USER_AGENT']."');";
			$db->query($sql);
			
			$res_arr = array(
				'code' => 200,
				'msg' => '登录成功',
			);
			die(json_encode($res_arr));
		}
	}
	else
	{
		$res_arr = array(
            'code' => 0,
			'msg' => '用户名或Email地址不存在'
		);
		die(json_encode($res_arr));
	}
}
?>